package com.jindi.jacococli.biz.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

/**
 * 重试组件
 * <p>
 * 文档 https://github.com/spring-projects/spring-retry
 *
 */
@Configuration
@EnableRetry
public class RetryConfig {

    private static final int MAX_ATTEMPTS = 3;
    private static final int BACK_OFF_PERIOD = 10;
    /**
     * 默认重试模版
     */
    @ConditionalOnMissingBean(name = "defaultRetryTemplate")
    @Bean(name = "defaultRetryTemplate")
    public RetryTemplate defaultRetryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();
        SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
        simpleRetryPolicy.setMaxAttempts(MAX_ATTEMPTS);
        retryTemplate.setRetryPolicy(simpleRetryPolicy);
        FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(BACK_OFF_PERIOD);
        retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
        retryTemplate.setThrowLastExceptionOnExhausted(true);
        return retryTemplate;
    }
}

///**
// * 重试组件示例
// */
//@Component
//public class Sample {
//
//    @Resource(name = "defaultRetryTemplate")
//    private RetryTemplate defaultRetryTemplate;
//
//    /**
//     * 捕获IllegalArgumentException异常进行重试，最大重试次数3，每次重试延迟10*（n-1)*2毫秒执行,n为重试次数
//     */
//    @Retryable(include = IllegalArgumentException.class,
//            maxAttempts = 3,
//            backoff = @Backoff(
//                    delay = 10,
//                    multiplier = 2
//            )
//    )
//    public Integer randomInt() {
//        int n = RandomUtils.nextInt(0, 2);
//        if (n == 0) {
//            throw new IllegalArgumentException();
//        }
//        return n;
//    }
//
//    public Integer outerRandomInt() {
//        return defaultRetryTemplate.execute(new RetryCallback<Integer, IllegalArgumentException>() {
//            @Override
//            public Integer doWithRetry(RetryContext retryContext) throws IllegalArgumentException {
//                int n = RandomUtils.nextInt(0, 2);
//                if (n == 0) {
//                    throw new IllegalArgumentException();
//                }
//                return n;
//            }
//        });
//    }
//}
